﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Bamboo.Helpers;

namespace VietThinks.Web.Mvc
{
    public static partial class HtmlHelperExtensions
    {
        public static CheckBoxBuilder<TModel> CheckBoxEx<TModel>(this HtmlHelper htmlHelper, Expression<Func<TModel, object>> expression)
        {
            return new CheckBoxBuilder<TModel>(htmlHelper, expression);
        }
    }

    public class CheckBoxBuilder<TModel> : HtmlInputElementBuilder<TModel>
    {
        internal CheckBoxBuilder(HtmlHelper htmlHelper, Expression<Func<TModel, object>> expression)
            : base(htmlHelper, expression)
        {
            this.value = this.expression.Compile()((TModel)htmlHelper.ViewData.Model);
        }

        protected override string BuildCore()
        {
            bool @checked = false;
            
            Boolean.TryParse(this.value.ToStringEx(), out @checked);

            return this.htmlHelper.CheckBox(htmlHelper.BuildBindingPath(this.expression), @checked, this.htmlAttributes).ToHtmlString();
        }                
    }
}
